package com.sap.sap_mangers.controller;

import com.sap.sap_mangers.dto.sapImage.SapImageDto;
import com.sap.sap_mangers.service.ImageService;
import com.sap.sap_mangers.until.SimpleJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 樊东升
 * @date 2022/8/23 17:33
 */
@RestController
@RequestMapping("/Image")
public class ImageController {
    @Autowired
    private ImageService imageService;

    @PreAuthorize("hasAuthority('正式成员')")
    @PostMapping("/addImage")
    public SimpleJson addImage(HttpServletRequest request) {
        List<MultipartFile> images = ((MultipartHttpServletRequest) request).getFiles("images");
        Set<MultipartFile> imageSet = new HashSet<>(images);
        List<MultipartFile> imagesNew = new ArrayList<>(imageSet);
        return imageService.addImage(imagesNew);
    }

    @PreAuthorize("hasAuthority('旧管理员')")
    @GetMapping("/getImageAudit")
    public SimpleJson getImageAudit() {
        return imageService.getImageAudit();
    }

    @PreAuthorize("hasAuthority('管理员')")
    @PostMapping("/passImage")
    public SimpleJson passImage(@RequestBody SapImageDto sapImageDto) {
        //把前端传过来的String转为Long
        try {
            List<Long> newData = new ArrayList<>();
            for (String s : sapImageDto.getImageId()) {
                long id = Long.parseLong(s);
                newData.add(id);
            }
            sapImageDto.setImageIdForLong(newData);
        } catch (Exception e) {
            return new SimpleJson(1, "id格式错误");
        }
        try {
            if (sapImageDto.getAudit() == 0) {
                imageService.passImage(sapImageDto);
            } else {
                imageService.noPassImage(sapImageDto);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return SimpleJson.FAILURE;
        }
        return SimpleJson.SUCCESS;
    }

    @PreAuthorize("hasAuthority('游客')")
    @GetMapping("/getImage")
    public SimpleJson getImage() {
        return new SimpleJson(imageService.getImage());
    }

    @PreAuthorize("hasAuthority('管理员')")
    @GetMapping("/deleteImage")
    public SimpleJson deleteImage(@RequestParam("id") String id) {
        try {
            long l = Long.parseLong(id);
            return imageService.deleteImage(l);
        } catch (Exception e) {
            e.printStackTrace();
            return new SimpleJson(1, "id格式错误");
        }

    }
}
